package glazedlists.chapter6;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.issuezilla.Issue;
import ca.odell.issuezilla.IssuezillaXMLParser;
import ca.odell.issuezilla.IssuezillaXMLParserHandler;

import java.io.IOException;
import java.io.InputStream;

public class IssuesLoader implements Runnable, IssuezillaXMLParserHandler {

    private EventList<Issue> issues = new BasicEventList<>();

    // get the list that issues are being loaded into
    public EventList<Issue> getIssues() {
        return issues;
    }

    public void load() {
        Thread backgroundThread = new Thread(this);
        backgroundThread.setName("Issues from resource");
        backgroundThread.setDaemon(true);
        backgroundThread.start();
    }

    @Override
    public void run() {
        IssuezillaXMLParser parser = new IssuezillaXMLParser();
        try (InputStream inputStream = IssuesLoader.class.getResourceAsStream("/issues.xml")) {
            parser.loadIssues(inputStream, this);
        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }
    }

    @Override
    public void issueLoaded(Issue issue) {
        issues.getReadWriteLock().writeLock().lock();
        try {
            issues.add(issue);
        } finally {
            issues.getReadWriteLock().writeLock().unlock();
        }
    }
}
